define(['../common/common','../common/pathCompute', 'ztree', 'text!../../pages/dataBase/materialService.html','text!../../pages/dataBase/materialServiceAdd.html'],function ($, pathfn, ztree, materialServiceHtml, materialServiceAddHtml){
  	var interface =  pathfn.interface,
  	tableHeight = $(window).height() - $('#budget-header').height() - $('.layui-footer').height() -80;	
  	var materialService = function(popId){ 
  		if(popId){
  			$('#' + popId.id).html(materialServiceHtml);
  		} else{
  			$('.page-content').html(materialServiceHtml); 
  		}	
	    layui.use([ 'table','form','laypage' ],function() {
	        var table = layui.table,
	        form = layui.form,
	        laypage = layui.laypage;
	      	init = function(){  
	       	 	ztreeOperateMate.ztreeInit();
	       	 	tableOperateMate.tableInit(popId);
	        	bindEvents();
	      	},
		    ztreeOperateMate = {
		      	setting: {
			        async: {
			            enable: true,
			            url: interface.ycaTree,
			            autoParam:["listCode='COST_CODE'","node=='root'"]
			        }, 
			        data: {
			          	key: {
			            	title: "",
			            	name: 'text'
			          	}
			    	},       
			        callback: {
			            onAsyncSuccess: function(event, treeId, treeNode, msg) {
		                    var treeObj = $.fn.zTree.getZTreeObj("tree-list2"),
		                    //获取ztree 所有节点
		                    getNodes = treeObj.getNodes();
		                    //获取ztree 第一个节点
		                    treeObj.selectNode(getNodes[0]);  
		                    //給第一个节点触发点击事件，显示右边table
		                    ztreeOperateMate.setting.callback.onClick('click','tree-list2',getNodes);
		                    //展开ztree
		                    treeObj.expandAll(true); 
		                    $('.content-loading').remove();       
		                },
		                onClick: function(even, treeId, treeNode) {

		                    var treeNode = treeNode[0] || treeNode;
		                    if (treeNode.level==0) {
		                    	if(!popId) $('.add-materialCode').slideUp(100);
		                    	tableOperateMate.tableReload({
		                    		lookTypeId:treeNode.id,
						            lookValueId:"",
						           	param2:"onelevel"
			                    });
		                    }else if (treeNode.level==1) {
		                    	if(!popId) $('.add-materialCode').slideDown(100);
		                    	tableOperateMate.tableReload({
		                    		lookTypeId:"",
						            lookValueId:treeNode.id,
						            param2:""
			                    });
		                    }
		                }
			        }
				},
      	ztreeInit: function(){  //加载左侧菜单树
        	$.fn.zTree.init($("#tree-list2"), this.setting); 		        	
      	}
			};
			tableOperateMate ={
				tableInitObj:function(popId){
					var colsHeight = [
						{field:'no', title: '序号', width:80, sort: true, align:'center'},
			            {field:'code', title: '编码', width:150, sort: true},
			            {field:'name', title: '名称', width:180},
			            {field:'type', title: '类别', width:80},
			            {field:'unit', title: '单位', width:80},
			            {field:'noPrice', title: '不含税单价', width:100},
			            {field:'price', title: '含税单价', width:100},
			            {field:'rate', title: '税率', width:100}
		            ];
		            if(popId){
		            	colsHeight.unshift({checkbox: true});
		            }else{
		            	colsHeight.push({field:'caozuo', title: '操作', width:80, align:'center', fixed:'right', toolbar: '#barDemo'});
		           	}
		            var obj = {
		              id: 'material-table',
		              elem: '#material-table', //指定原始表格元素选择器（推荐id选择器）
		              height: tableHeight, //容器高度
		              cols:  [colsHeight],
		              url: interface.ycaTableInfo,
		              method: 'get',
		              page: true, //开启分页
		              initSort: {
		                field: 'id' //排序字段，对应 cols 设定的各字段名
		                ,type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
		              },
		              limit: 20, //默认采用60
		              loading: true
		            }
		            return obj;           
			    },
				tableInit:function(popId){
	      			var _this = this,
		            defaults = {
		              where: {
		                lookTypeId:"",
		                lookValueId:"",
		                param2:""
		              },
		              done: function(res, curr, count){ 
		              	_this.listEdit(_this.tableInitObj()); 
		              }
		            };
		            $.extend(true, defaults, _this.tableInitObj(popId));        
		            table.render(defaults);
		            _this.tableEdit();              
	    		},
		        tableReload:function(where){
		        	table.reload('material-table',{
		        		where:where
		        	});
		        },
		        tableAdd:function(){
		        	var _this=this;
		        	var zTree = $.fn.zTree.getZTreeObj("tree-list2"),
					node = zTree.getSelectedNodes()[0];
		        	var layeradd=layer.open({
								type : 1,
								title : "新增",
								content : materialServiceAddHtml,
								fixed : true,
								skin: 'lay-padding',
								scrollbar : true,
								btn : [ '确定', '取消' ],
								area: '400px',
								yes : function(index, layero) {
										$('.ycasubmit').trigger('click');
								},
								btn2 : function(index, layero) {
								},
								success : function(index,layero) {
									$("input[name='lookvalue_id']").val(node.id);
									form.render();
									// console.log(node)
									materialVerify(node.getParentNode().id);
									form.on('submit(ycasubmit)', function(data){
						                var formData = data.field;
						                $.ajaxRequest({
						                    url: interface.ycaTableEdit,
						                    data:formData,
						                    successfn: function(data) {
						                      if (data.success==true) {
						                      	layer.msg("增加成功");
						                      	layer.close(layeradd);
						                      }else{
						                      	layer.msg(data.msg);
						                      }
						                      _this.tableReload({
						                      	lookTypeId:"",
										                lookValueId:node.id,
										                param2:""
						                      });
						                    },
						                    errorfn: function(data){
						                      console.log(data);
						                    }
						                })
						                return false;
						            });
								}
							});
		        },
		        tableEdit:function(){
		        	table.on('tool(materialCodeEvent)', function(obj){
		              	var dataObj = obj.data;
		              	if(obj.event === 'edit'){
			                var layeredit=layer.open({
								type : 1,
								title : "修改",
								content : materialServiceAddHtml,
								fixed : true,
								skin: 'lay-padding',
								scrollbar : true,
								btn : [ '确定', '取消' ],
								area: '400px',
								yes : function(index, layero) {
									$('.ycasubmit').trigger('click');
								},
								btn2 : function(index, layero) {
								},
								success : function(index,layero) {
									$("input[name='cmd']").val("edit");
									$("input[name='lookvalue_id']").val(dataObj.lookvalue_id);
									$("input[name='id']").val(dataObj.id);
									$("input[name='code']").val(dataObj.code).attr("disabled",true);
									$("input[name='name']").val(dataObj.name);
									$("input[name='unit']").val(dataObj.unit);
									$("input[name='price']").val(dataObj.price);
									$("input[name='rate']").val(dataObj.rate);
									form.render();
									materialVerify("edit");
									form.on('submit(ycasubmit)', function(data){
					                    var formData = data.field;
					                    $.ajaxRequest({
					                        url: interface.ycaTableEdit,
					                        data:formData,
					                        successfn: function(data) {
					                        	if (data.success==true) {
							                      	layer.msg("修改成功");
							                      	layer.close(layeredit);
							                      }else{
							                      	layer.msg(data.msg);
							                      }
				                          	obj.update({
					                            name: formData.name,
					                            unit: formData.unit,
					                            price: formData.price,
					                            rate: formData.rate
						                        });
					                        },
					                        errorfn: function(data){
					                          	console.log(data);
					                        }
					                    })
			                      		layer.close(layeredit);
			                      		return false;
			                    	});
								}
							});
		            	}
	            	});
	    		},
	    		listEdit: function($obj){
	              	var elem = $obj.elem,
	              	$caozuo = $(elem).next('.layui-table-view');
	              	if(!$caozuo.find('.caozuo-vis').length){
		                pathfn._toggleVisInit($obj.cols,$obj.elem,function(){
		                  form.render();
		                });
	              	}else{
		                var inputArr = $caozuo.find('.caozuo-vis').find("input[type='checkbox']");
		                for(var i=0; i< inputArr.length; i++){
		                  	var ischecked = inputArr.eq(i).prop('checked'),
		                    field = $(inputArr[i]).data('field');
		                  	if(ischecked){                
		                    	$caozuo.find('td[data-field="'+field+'"],th[data-field="'+field+'"]').hide(0);
		                  	}else{
		                    	$caozuo.find('td[data-field="'+field+'"],th[data-field="'+field+'"]').show(0);
		                  	}
		                }
	              	}
		        }
			}
			bindEvents=function(){
				$(".add-materialCode").bind("click", function(event){
					tableOperateMate.tableAdd();
				});
				form.verify({
				    decimal: function(value){
				    	var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
				    	if(!reg.test(value)){
				        	return '分值必须是非负数字';
				     	}
				    }
				})
			};
			materialVerify=function(lookTypeId){
				form.verify({
				  code: function(value, item){ //value锛氳〃鍗曠殑鍊笺�乮tem锛氳〃鍗曠殑DOM瀵硅薄
				  	if (lookTypeId=="edit") {
				    }else{
				    	var i="^"+(lookTypeId+5)+"0[0-9]{4}";
				    	console.log(i)
				    	if(!new RegExp(i).test(value)){
					      return '编码格式为'+(lookTypeId+5)+"0XXXX...";
					    }
					  }
				  }
				});
			};
		  	init();
		})
	}
  	return materialService;
})
